package com.idcard.huashi;


import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.zysoft.function.ApiUtil;
import com.zysoft.function.Stroage;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.net.SocketTimeoutException;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class MainActivity extends Activity {

    private TextView tv_title;//标题栏
    private ImageView title_btn;//标题栏按钮
    private Dialog loadingDialog;
    public ApiUtil apiUtil;
    private Stroage stroage;
    private Context context;
    private Button LogBtn;//登录按钮
    private EditText et_user_name;//账号
    private EditText et_psw;//密码
    public static final int SUCCEED = 0;
    public static final int FAILE = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);// 去掉标题栏 使用自定义标题栏;
        if (Build.VERSION.SDK_INT >= 21) {//21表示5.0
            Window window = getWindow();
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(Color.TRANSPARENT);
        }
        context = this;
        stroage = new Stroage();
        apiUtil = new ApiUtil();
        initView();
        initEvent();
    }
    private void initView() {
        // TODO Auto-generated method stub
        setContentView(R.layout.fragment_submit);
        loadingDialog = new Dialog(this, R.style.MyDialogStyle);// 创建自定义样式dialog
        tv_title =  findViewById(R.id.tv_title);//标题栏
        LogBtn = findViewById(R.id.btn_login);//登录按钮
        title_btn = findViewById(R.id.img_btn);
        et_user_name = findViewById(R.id.et_user_name);
        et_psw = findViewById(R.id.et_psw);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            requestPermissions(new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}, 0);
        }
        if (stroage.getUser(context) != null && stroage.getPassword(context) != null) {
            et_user_name.setText(stroage.getUser(context).toString());
            et_psw.setText(stroage.getPassword(context).toString());
        }
    }
    //事件点击
    private void initEvent() {
        // TODO Auto-generated method stub
        LogBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (TextUtils.isEmpty(et_user_name.getText().toString().trim())) {
                    apiUtil.ShowToast("账号不能为空");
                    return;
                }
                if (TextUtils.isEmpty(et_psw.getText().toString().trim())) {
                    apiUtil.ShowToast("密码不能为空");
                    return;
                }
                apiUtil.ShowLoading("在线登录中...", context);
                Ajax(et_user_name.getText().toString(), et_psw.getText().toString());
            }
        });

    }
    //接口请求
    public void Ajax(String... params) {
        OkHttpClient client = new OkHttpClient.Builder()//创建OkHttpClient对象
                .connectTimeout(20, TimeUnit.SECONDS)//连接超时时间 单位 S
                .readTimeout(20,TimeUnit.SECONDS)//读取超时时间 单位 S
                .build();
        RequestBody requestBody = new FormBody.Builder()
                .add("username", et_user_name.getText().toString().trim())
                .add("password", et_psw.getText().toString().trim())
                .build();
        Request request = new Request.Builder()
                .addHeader("___IGNORE_VERIFICATION_CODE___", "true")
                .url(apiUtil.Login)
                .post(requestBody)
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.d("zysoft", "responseCode" + "   " + response.code() + " responseMessage" + response.message());
                mHandler.sendMessage(mHandler.obtainMessage(SUCCEED, response.body().string()));
            }
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("zysoft", String.valueOf(e));
                Log.e("zysoft","请求失败"+e.getMessage());
                if (e instanceof SocketTimeoutException) {
                    mHandler.sendMessage(mHandler.obtainMessage(FAILE, "请求超时"));
                } else {
                    mHandler.sendMessage(mHandler.obtainMessage(FAILE, "连接异常"));
                }
            }
        });
    }
    public void Targer() {
        Intent intent = new Intent(this, ProjectFragment.class);
        startActivity(intent);
        finish();
    }
    @SuppressLint("HandlerLeak")
    public final Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case SUCCEED: {
                    apiUtil.HideLoading();
                    Log.e(apiUtil.dateTime(), "登录日志" + msg.obj.toString());
                    try {
                        JSONObject json = new JSONObject(msg.obj.toString());
                        if (json.has("code") && (json.getInt("code") == 200)) {
                            Log.e(apiUtil.dateTime(), "登录成功");
                            stroage.setUser(et_user_name.getText().toString().trim(), context);//当前账号
                            stroage.setPassword(et_psw.getText().toString().trim(), context);//当前登录密码
                            Targer();
                        } else {
                            apiUtil.ShowToast(json.getString("content"));//登录错误提示
                            return;
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    break;
                }
                case FAILE: {
                    apiUtil.HideLoading();
                    apiUtil.ShowToast(msg.obj.toString());
                    break;
                }
            }
        }
    };

}
